/*
 ============================================================================
 Name        : algo_1.c
 Author      : Ashok
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DEBUG 0		/* 0: No Debug; 1: Debug input loading */
#define PROBLEM 0 	/* 0: Sort; 1: MaxSubArray */
#include "sort.h"

/* Function declarations */
static int getInput(int **in);
static void setOutput(int *in, int inSize);

int main(void) {
	int *in; /* Input and Output arrays for sorting */
	int inSize; /* Size of the array */
	time_t start, end; /* Time objects to monitor sort performance */
	double dif; /* Time objects to monitor sort performance */
#if PROBLEM == 1
	subArr_t ret; /* Object to get maximum subArray */
#endif

	inSize = getInput(&in);
	time(&start);
#if PROBLEM == 0
	heapSort(in, inSize);
	time(&end);
	setOutput(in, inSize);
#else
	ret = maxSubArrayLinTime(in, inSize);
	time(&end);
	printf("\nStart: %d, End: %d, Max Value: %d\n",ret.stIdx, ret.endIdx, ret.sArrVal);
#endif

	dif = difftime(end, start);
	printf("\nProgram execution time: %f s\n", dif);
	return 0;
}

int getInput(int **inp) {
	FILE *fp;
	int *in;
	int noOfIn;
	int idx, tmp;
	puts("START OF PROGRAM");

	fp = fopen("D:/09_Projects/AlgoEcp/algo_1/src/sortInput.csv", "r");
	if(fp == NULL)
		printf("file not found");
	else {
		fscanf(fp, "%d", &noOfIn);
#if DEBUG == 1
		printf("No of input numbers: %d\n", noOfIn);
#endif
		in = NULL;
		in = (int*)malloc(noOfIn * sizeof(int));
		if(in == NULL) {
			printf("Memory not allocated\n");
			exit(EXIT_FAILURE);
		}
		else {
			*inp = in;
			for(idx = 0; idx < noOfIn; idx++) {
				fscanf(fp, "%d", &tmp);
				in[idx] = tmp;
#if DEBUG == 1
				printf("Input %d: %d , %d\n", idx, in[idx], tmp);
#endif
			}
		}
	}
	fclose(fp);
	return noOfIn;
}


static void setOutput(int *in, int noOfIn) {
	FILE *fp;
	int idx;
	puts("Writing output to buffer");

	fp = fopen("D:/09_Projects/AlgoEcp/algo_1/src/sortOutput.csv", "w");
	if(fp == NULL)
		printf("file not found");
	else {
		fprintf(fp, "%d", noOfIn);
		for(idx = 0; idx < noOfIn; idx++) {
			fprintf(fp, "\n%d", in[idx]);
		}
	}
	fclose(fp);
	free(in);
}


